package com.cqyanyu.yanyu.view.recyclerView;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.cqyanyu.yanyu.R;

import java.util.List;

/**
 * Created by cheng on 2016/7/16.
 */
public class YRecyclerView extends SwipeRefreshLayout implements SwipeRefreshLayout.OnRefreshListener {
    protected RecyclerView mRecyclerView;
    protected YRecyclerViewAdapter mYRecyclerViewAdapter;
    private RecyclerView.OnScrollListener mScrollListener;
    private boolean isLoading;//当前是否加载中
    private boolean loadMoreEnabled = true;//加载跟多开关
    private OnLoadMoreListener onLoadMoreListener;
    private OnRefreshListener onRefreshListener;
    private RecyclerView.LayoutManager layout;

    public YRecyclerView(Context context) {
        super(context);
        init();
    }

    public YRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mRecyclerView = new RecyclerView(getContext());
        addView(mRecyclerView);
        setEnabled(false);
        super.setOnRefreshListener(this);
        setColorSchemeColors(getAttrColor(R.attr.colorPrimary), getAttrColor(R.attr.colorPrimaryDark), getAttrColor(R.attr.colorAccent));
        setColorSchemeColors(Color.RED, Color.RED);
        initOnScrollListener();
    }

    /**
     * 获取attr 颜色
     *
     * @param attr
     * @return
     */
    private int getAttrColor(int attr) {
        TypedValue typedValue = new TypedValue();
        int[] attribute = new int[]{attr};
        TypedArray array = getContext().obtainStyledAttributes(typedValue.resourceId, attribute);
        int color0 = array.getColor(0 /* index */, 0xffffffff /* default size */);
        array.recycle();
        return color0;
    }

    /**
     * 设置一个新的适配器以提供对需求的子视图。
     *
     * @param adapter
     */
    public void setAdapter(YRecyclerViewAdapter adapter) {
        mYRecyclerViewAdapter = adapter;
        mRecyclerView.setAdapter(adapter);
    }

    private void initAdapter() {
        if (mYRecyclerViewAdapter == null) {
            layout = new GridLayoutManager(getContext(), 1);
            mRecyclerView.setLayoutManager(layout);
            setAdapter(new YRecyclerViewAdapter());
        }
    }

    public void setLayoutManager(RecyclerView.LayoutManager layout) {
        this.layout = layout;
        mRecyclerView.setLayoutManager(layout);
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    /**
     * 初始化滚动 加载更多
     */
    private void initOnScrollListener() {

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mScrollListener != null) {
                    mScrollListener.onScrolled(recyclerView, dx, dy);
                }
                if (!isLoading && loadMoreEnabled && layout != null && layout instanceof LinearLayoutManager) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layout;
                    int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                    int totalItemCount = linearLayoutManager.getItemCount();
                    //lastVisibleItem >= totalItemCount - 1 表示剩下1个item自动加载，各位自由选择
                    // dy>0 表示向下滑动
                    if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {
                        onLoadMore();
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mScrollListener != null) {
                    mScrollListener.onScrollStateChanged(recyclerView, newState);
                }
            }
        });

    }

    public YRecyclerViewAdapter getAdapter() {
        return mYRecyclerViewAdapter;
    }

    /**
     * 绑定指定数据类型的 viewHolder
     *
     * @param entityClass     数据实体类的class
     * @param viewholderClass viewHolder的实体类
     */
    public void bindItemHolder(Class entityClass, Class<? extends YViewHolder> viewholderClass) {
        initAdapter();
        mYRecyclerViewAdapter.bindItemHolder(entityClass, viewholderClass);
    }


    /**
     * 设置列数
     *
     * @param spanCount
     */
    public void setSpanCount(int spanCount) {
        if (layout != null) {
            ((GridLayoutManager) layout).setSpanCount(spanCount);
        }
    }

    /**
     * 设置对应类型的cell所占宽度
     *
     * @param entityClass
     * @param spanSize
     */
    public void setCellSpanCount(Class entityClass, int spanSize) {
        mYRecyclerViewAdapter.setCellSpanCount(entityClass, spanSize);
    }

    /**
     * itemviewType接口
     *
     * @param entityClass    数据实体类class
     * @param onItemViewType type接口
     */
    public void setOnItemViewType(Class entityClass, YRecyclerViewAdapter.OnItemViewType onItemViewType) {
        mYRecyclerViewAdapter.setOnItemViewType(entityClass, onItemViewType);
    }

    /**
     * 设置data，可以是多个不同类型的List
     *
     * @param lists List列表
     */
    public void setData(List... lists) {
        mYRecyclerViewAdapter.setData(lists);
    }

    /**
     * 添加list数据
     *
     * @param list
     */
    public void addData(List list) {
        mYRecyclerViewAdapter.addData(list);
    }

    /**
     * 添加单项数据
     *
     * @param object
     */
    public void addItemData(Object object) {
        mYRecyclerViewAdapter.addItemData(object);
    }

    /**
     * 设置header 的list数据
     *
     * @param headerlist
     */
    public void setHeaderList(List headerlist) {
        this.mYRecyclerViewAdapter.setHeaderList(headerlist);
    }

    /**
     * 更新header
     *
     * @param index  指定序号
     * @param object
     */
    public void setHeader(int index, Object object) {
        this.mYRecyclerViewAdapter.setHeader(index, object);
    }

    /**
     * 添加header 在header最后一条
     *
     * @param object
     */
    public void addHeader(Object object) {
        this.mYRecyclerViewAdapter.addHeader(object);
    }

    public void addHeader(int index, Object object) {
        this.mYRecyclerViewAdapter.addHeader(index, object);
    }

    /**
     * 刷新事件
     *
     * @param onRefreshListener
     */
    @Override
    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        setEnabled(true);
        this.onRefreshListener = onRefreshListener;
    }

    /**
     * 设置加载更多状态
     *
     * @param loadMore
     */
    public void setLoadMore(boolean loadMore) {
        loadMoreEnabled = loadMore;
        mYRecyclerViewAdapter.setLoadMore(loadMore);
    }

    /**
     * 加载更多状态
     *
     * @return
     */
    public boolean isLoadMore() {
        return mYRecyclerViewAdapter.isLoadMore();
    }


    /**
     * 加载完成
     */
    public void loadFinish() {
        isLoading = false;
//        setEnabled(true);
    }


    /**
     * 设置加载更多接口
     *
     * @param onLoadMoreListener
     */
    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    /**
     * 设置是否没有数据是提示
     *
     * @param noDataTips
     */
    public void setNoDataTips(boolean noDataTips) {
        mYRecyclerViewAdapter.setNoDataTips(noDataTips);
    }

    /**
     * 没有数据是提示
     *
     * @return
     */
    public boolean isNoDataTips() {
        return mYRecyclerViewAdapter.isNoDataTips();
    }

    @Override
    public void setRefreshing(boolean refreshing) {
        super.setRefreshing(refreshing);
        if (loadMoreEnabled) {
            mYRecyclerViewAdapter.setLoadMore(!refreshing);
        }
    }

    /**
     * 设置滚动事件
     *
     * @param mScrollListener
     */
    public void setOnScrollListener(RecyclerView.OnScrollListener mScrollListener) {
        this.mScrollListener = mScrollListener;
    }

    @Override
    public void onRefresh() {
        setLoadMore(false);
        if (onRefreshListener != null) {
            onRefreshListener.onRefresh();
        }
    }

    private void onLoadMore() {
        isLoading = true;
//        setEnabled(false);
        if (mYRecyclerViewAdapter != null) {
            mYRecyclerViewAdapter.setLoadMore(isLoading);
        }
        if (onLoadMoreListener != null) {
            onLoadMoreListener.onLoadMore();
        }
    }

    public void notifyDataSetChanged() {
        mYRecyclerViewAdapter.notifyDataSetChanged();
    }

    public void notifyItemChanged(int position) {
        mYRecyclerViewAdapter.notifyItemChanged(position);
    }

    public interface OnLoadMoreListener {
        public void onLoadMore();
    }
}
